package com.campus.lostandfound.config;

import com.campus.lostandfound.utils.AesUtil;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;

import java.util.HashMap;
import java.util.Map;

/**
 * 加密环境变量后处理器
 * 在 Spring Boot 启动时自动解密 ENC(...) 格式的环境变量
 */
public class EncryptedEnvironmentPostProcessor implements EnvironmentPostProcessor {

    private static final String ENCRYPTED_PROPERTY_SOURCE_NAME = "decryptedProperties";

    // 需要解密的环境变量名称列表
    private static final String[] ENCRYPTED_PROPERTIES = {
        "DB_URL",
        "DB_PASSWORD",
        "REDIS_PASSWORD"
    };

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        try {
            // 获取 AES 密钥
            String aesKey = environment.getProperty("AES_ENCRYPTION_KEY");
            if (aesKey == null || aesKey.isEmpty()) {
                System.out.println("⚠ 警告: 未检测到 AES_ENCRYPTION_KEY，跳过环境变量解密");
                return;
            }

            // 解密配置
            Map<String, Object> decryptedProperties = new HashMap<>();
            boolean hasEncryptedValue = false;

            for (String propertyName : ENCRYPTED_PROPERTIES) {
                String value = environment.getProperty(propertyName);
                
                if (value != null && !value.isEmpty()) {
                    if (AesUtil.isEncrypted(value)) {
                        try {
                            // 提取密文并解密
                            String ciphertext = AesUtil.extractCiphertext(value);
                            String decrypted = AesUtil.decrypt(ciphertext, aesKey);
                            decryptedProperties.put(propertyName, decrypted);
                            hasEncryptedValue = true;
                            
                            System.out.println("✓ 成功解密: " + propertyName);
                        } catch (Exception e) {
                            System.err.println("✗ 解密失败: " + propertyName + " - " + e.getMessage());
                            throw new RuntimeException("配置项解密失败: " + propertyName, e);
                        }
                    }
                }
            }

            // 如果有解密的配置，添加到环境中（优先级最高）
            if (hasEncryptedValue) {
                PropertySource<?> propertySource = new MapPropertySource(
                    ENCRYPTED_PROPERTY_SOURCE_NAME, 
                    decryptedProperties
                );
                environment.getPropertySources().addFirst(propertySource);
                System.out.println("✓ 环境变量解密完成");
            }

        } catch (Exception e) {
            System.err.println("✗ 环境变量解密过程出错: " + e.getMessage());
            throw new RuntimeException("环境变量解密失败", e);
        }
    }
}

